package yxk.task;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.exception.KDException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.sdk.plugin.Plugin;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 考勤档案组织长名称
 */
public class WtpAttfileBaseTask extends AbstractTask implements Plugin {
    private static final Log LOG = LogFactory.getLog(WtpAttfileBaseTask.class);
    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        LOG.info("======进入=======");
        DynamicObject[] load = BusinessDataServiceHelper.load("wtp_attfilebase", "adminorg,nwg5_orgname", null);
        LOG.info("EmpPosorgrelNameTask.execute.load:{}",load);
        List<DynamicObject> list=new ArrayList<>();
        for (int i=0; i < load.length ;i++) {
            DynamicObject adminorg = load[i].getDynamicObject("adminorg");
            LOG.info("EmpPosorgrelNameTask.execute.adminorg:{}",adminorg);
            if(adminorg == null){
                continue;
            }
            String orgName = getOrgName(adminorg);
            orgName = orgName.substring(1);
            LOG.info("EmpPosorgrelNameTask.execute.highjobgrade:{}",orgName);
            load[i].set("nwg5_orgname",orgName);//组织长名称
            list.add(load[i]);
        }
        DynamicObject[] dataEntities=new DynamicObject[list.size()];
        for (int i = 0; i < list.size(); i++) {
            dataEntities[i]=list.get(i);
        }
        SaveServiceHelper.update(dataEntities);
    }

    public String getOrgName(DynamicObject adminorg){
        StringBuffer orgName=new StringBuffer();
        DynamicObject org = BusinessDataServiceHelper.loadSingle(adminorg.getPkValue(), adminorg.getDynamicObjectType().getName());
        //获取上级行政组织
        DynamicObject parent = org.getDynamicObject("parent");
        if(parent != null) {
            String orgName1 = getOrgName(parent);
            orgName.append(orgName1);
        }
        orgName.append("_");
        orgName.append(org.getString("name"));
        return orgName.toString();
    }
}